package org.example.project

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Button
import androidx.compose.material.ButtonDefaults
import androidx.compose.material.Card
import androidx.compose.material.Checkbox
import androidx.compose.material.CheckboxDefaults
import androidx.compose.material.Divider
import androidx.compose.material.FloatingActionButton
import androidx.compose.material.Icon
import androidx.compose.material.MaterialTheme
import androidx.compose.material.OutlinedTextField
import androidx.compose.material.Scaffold
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.material.TextButton
import androidx.compose.material.TextFieldDefaults
import androidx.compose.material.TopAppBar
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.lightColors
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Dialog
import kotlinx.datetime.LocalDate
import org.example.project.components.ClassSelector
import org.example.project.components.MonthYearPicker
import org.example.project.model.FeeRecord
import org.example.project.viewmodel.FeeViewModel
import org.jetbrains.compose.ui.tooling.preview.Preview
import kotlin.math.round

@Composable
@Preview
fun App() {
    val viewModel = remember { FeeViewModel() }
    val feeRecordsByClass by viewModel.feeRecordsByClass.collectAsState(emptyMap())
    var showAddDialog by remember { mutableStateOf(false) }

    // 自定义会计软件主题
    val accountingTheme = lightColors(
        primary = Color(0xFF2E5090),        // 深蓝色作为主色调
        primaryVariant = Color(0xFF1A3A75), // 更深的蓝色
        secondary = Color(0xFF4CAF50),      // 绿色作为辅助色
        background = Color(0xFFF5F7FA),     // 浅灰蓝色背景
        surface = Color.White,              // 白色表面
        error = Color(0xFFB00020),          // 标准错误色
        onPrimary = Color.White,            // 主色上的文字为白色
        onSecondary = Color.White,          // 辅助色上的文字为白色
        onBackground = Color(0xFF1F1F1F),   // 背景上的文字为深灰色
        onSurface = Color(0xFF1F1F1F),      // 表面上的文字为深灰色
        onError = Color.White               // 错误色上的文字为白色
    )

    MaterialTheme(colors = accountingTheme) {
        Scaffold(
            topBar = {
                TopAppBar(
                    title = { Text("幼儿园费用管理系统") }
                )
            },
            floatingActionButton = {
                FloatingActionButton(onClick = { showAddDialog = true }) {
                    Icon(Icons.Default.Add, contentDescription = "添加")
                }
            }
        ) { padding ->
            Column(modifier = Modifier.padding(padding).fillMaxSize()) {
                // 按班级分类显示费用记录
                ClassBasedFeeDisplay(feeRecordsByClass = feeRecordsByClass)

                // 总金额显示
//                TotalAmountDisplay(viewModel = viewModel)
            }
        }

        // 添加记录对话框
        if (showAddDialog) {
            AddFeeRecordDialog(
                onDismiss = { showAddDialog = false },
                onConfirm = { record ->
                    viewModel.addFeeRecord(record)
                    showAddDialog = false
                },
                currentDate = viewModel.currentDate
            )
        }
    }
}

// 移除功能区布局

@Composable
fun SummaryTable(feeRecords: List<FeeRecord>) {
    Card(
        modifier = Modifier.fillMaxWidth().padding(16.dp),
        elevation = 4.dp,
        backgroundColor = MaterialTheme.colors.surface,
        shape = RoundedCornerShape(8.dp)
    ) {
        Column(modifier = Modifier.padding(16.dp)) {
            Text(
                "费用汇总表",
                fontSize = 20.sp,
                fontWeight = FontWeight.Bold,
                color = MaterialTheme.colors.primary
            )
            Spacer(modifier = Modifier.height(16.dp))

            // 表头
            Surface(
                color = MaterialTheme.colors.primary.copy(alpha = 0.1f),
                modifier = Modifier.fillMaxWidth(),
                shape = RoundedCornerShape(4.dp)
            ) {
                Row(modifier = Modifier.fillMaxWidth().padding(12.dp)) {
                    TableHeaderCell(text = "日期", modifier = Modifier.weight(1f))
                    TableHeaderCell(text = "班级", modifier = Modifier.weight(1f))
                    TableHeaderCell(text = "收费标准", modifier = Modifier.weight(1f))
                    TableHeaderCell(text = "人数", modifier = Modifier.weight(0.7f))
                    TableHeaderCell(text = "满勤", modifier = Modifier.weight(0.7f))
                    TableHeaderCell(text = "上课天数", modifier = Modifier.weight(0.7f))
                    TableHeaderCell(text = "金额", modifier = Modifier.weight(1f))
                }
            }

            // 表格内容
            if (feeRecords.isEmpty()) {
                Box(
                    modifier = Modifier.fillMaxWidth().height(100.dp),
                    contentAlignment = Alignment.Center
                ) {
                    Text("暂无数据", color = MaterialTheme.colors.onSurface.copy(alpha = 0.6f))
                }
            } else {
                LazyColumn {
                    items(feeRecords) { record ->
                        Row(
                            modifier = Modifier.fillMaxWidth().padding(vertical = 8.dp),
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            // 显示年月而不是完整日期
                            TableCell(
                                text = "${record.date.year}年${record.date.monthNumber}月",
                                modifier = Modifier.weight(1f)
                            )
                            TableCell(text = record.className, modifier = Modifier.weight(1f))
                            TableCell(
                                text = "¥${record.feeStandard}",
                                modifier = Modifier.weight(1f)
                            )
                            TableCell(
                                text = "${record.studentCount}",
                                modifier = Modifier.weight(0.7f)
                            )
                            TableCell(
                                text = if (record.isFullAttendance) "是" else "否",
                                modifier = Modifier.weight(0.7f)
                            )
                            TableCell(
                                text = "${record.attendanceDays}",
                                modifier = Modifier.weight(0.7f)
                            )
                            TableCell(
                                text = "¥${(round(record.amount * 100) / 100).toString()}",
                                modifier = Modifier.weight(1f),
                                color = MaterialTheme.colors.primary
                            )
                        }
                        Divider(color = MaterialTheme.colors.onSurface.copy(alpha = 0.1f))
                    }
                }
            }
        }
    }
}

@Composable
fun TableHeaderCell(text: String, modifier: Modifier) {
    Text(
        text = text,
        fontSize = 14.sp,
        modifier = modifier,
        fontWeight = FontWeight.Bold,
        color = MaterialTheme.colors.primary,
        textAlign = TextAlign.Center
    )
}

@Composable
fun TableCell(text: String, modifier: Modifier, color: Color = Color.Unspecified) {
    Text(
        text = text,
        modifier = modifier,
        fontSize = 14.sp,
        color = color,
        textAlign = TextAlign.Center
    )
}

@Composable
fun TotalAmountDisplay(viewModel: FeeViewModel) {
    val totalAmount = remember(viewModel.feeRecords.collectAsState().value) {
        viewModel.calculateTotalAmount()
    }

    Card(
        modifier = Modifier.fillMaxWidth().padding(16.dp),
        elevation = 4.dp,
        backgroundColor = MaterialTheme.colors.primary,
        shape = RoundedCornerShape(8.dp)
    ) {
        Row(
            modifier = Modifier.padding(20.dp).fillMaxWidth(),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ) {
            Text(
                "总金额",
                fontSize = 20.sp,
                fontWeight = FontWeight.Bold,
                color = MaterialTheme.colors.onPrimary
            )
            Text(
                "¥${(round(totalAmount * 100) / 100).toString()}",
                fontSize = 28.sp,
                fontWeight = FontWeight.Bold,
                color = MaterialTheme.colors.onPrimary
            )
        }
    }
}

@Composable
fun AddFeeRecordDialog(
    onDismiss: () -> Unit,
    onConfirm: (FeeRecord) -> Unit,
    currentDate: LocalDate
) {
    var className by remember { mutableStateOf("") }
    var feeStandard by remember { mutableStateOf("") }
    var studentCount by remember { mutableStateOf("") }
    var isFullAttendance by remember { mutableStateOf(true) }
    var attendanceDays by remember { mutableStateOf("22") }
    var selectedDate by remember { mutableStateOf(currentDate) }

    // 计算金额
    val amount = remember(feeStandard, studentCount, isFullAttendance, attendanceDays) {
        try {
            val fee = feeStandard.toDoubleOrNull() ?: 0.0
            val count = studentCount.toIntOrNull() ?: 0
            val days = attendanceDays.toIntOrNull() ?: 22

            if (isFullAttendance) {
                fee * count
            } else {
                (fee * count / 22.0) * days
            }
        } catch (e: Exception) {
            0.0
        }
    }

    Dialog(onDismissRequest = onDismiss) {
        Surface(
            shape = MaterialTheme.shapes.medium,
            color = MaterialTheme.colors.surface,
            elevation = 8.dp
        ) {
            Column(modifier = Modifier.padding(20.dp)) {
                Text(
                    "添加新记录",
                    fontSize = 20.sp,
                    fontWeight = FontWeight.Bold,
                    color = MaterialTheme.colors.primary
                )
                Spacer(modifier = Modifier.height(20.dp))

                // 班级选择器
                ClassSelector(
                    selectedClass = className,
                    onClassSelected = { className = it },
                    modifier = Modifier.fillMaxWidth()
                )
                Spacer(modifier = Modifier.height(16.dp))

                // 收费标准
                OutlinedTextField(
                    value = feeStandard,
                    onValueChange = { feeStandard = it },
                    label = { Text("收费标准") },
                    modifier = Modifier.fillMaxWidth(),
                    colors = TextFieldDefaults.outlinedTextFieldColors(
                        focusedBorderColor = MaterialTheme.colors.primary,
                        unfocusedBorderColor = MaterialTheme.colors.primary.copy(alpha = 0.5f),
                        cursorColor = MaterialTheme.colors.primary
                    )
                )
                Spacer(modifier = Modifier.height(16.dp))

                // 年月选择器
                MonthYearPicker(
                    selectedDate = selectedDate,
                    onDateSelected = { selectedDate = it },
                    modifier = Modifier.fillMaxWidth()
                )
                Spacer(modifier = Modifier.height(16.dp))

                // 人数
                OutlinedTextField(
                    value = studentCount,
                    onValueChange = { studentCount = it },
                    label = { Text("人数") },
                    modifier = Modifier.fillMaxWidth(),
                    colors = TextFieldDefaults.outlinedTextFieldColors(
                        focusedBorderColor = MaterialTheme.colors.primary,
                        unfocusedBorderColor = MaterialTheme.colors.primary.copy(alpha = 0.5f),
                        cursorColor = MaterialTheme.colors.primary
                    )
                )
                Spacer(modifier = Modifier.height(16.dp))

                // 满勤选项
                Row(verticalAlignment = Alignment.CenterVertically) {
                    Checkbox(
                        checked = isFullAttendance,
                        onCheckedChange = { isFullAttendance = it },
                        colors = CheckboxDefaults.colors(checkedColor = MaterialTheme.colors.primary)
                    )
                    Text("满勤(22天)", color = MaterialTheme.colors.onSurface)
                }

                // 非满勤时显示上课天数输入框
                if (!isFullAttendance) {
                    Spacer(modifier = Modifier.height(8.dp))
                    OutlinedTextField(
                        value = attendanceDays,
                        onValueChange = { attendanceDays = it },
                        label = { Text("上课天数") },
                        modifier = Modifier.fillMaxWidth(),
                        colors = TextFieldDefaults.outlinedTextFieldColors(
                            focusedBorderColor = MaterialTheme.colors.primary,
                            unfocusedBorderColor = MaterialTheme.colors.primary.copy(alpha = 0.5f),
                            cursorColor = MaterialTheme.colors.primary
                        )
                    )
                }

                // 显示计算的金额
                Spacer(modifier = Modifier.height(16.dp))
                Card(
                    modifier = Modifier.fillMaxWidth(),
                    backgroundColor = MaterialTheme.colors.primary.copy(alpha = 0.1f),
                    elevation = 0.dp
                ) {
                    Row(
                        modifier = Modifier.padding(12.dp).fillMaxWidth(),
                        horizontalArrangement = Arrangement.SpaceBetween,
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Text(
                            "金额:",
                            fontWeight = FontWeight.Medium,
                            color = MaterialTheme.colors.onSurface
                        )
                        Text(
                            "¥${(round(amount * 100) / 100).toString()}",
                            fontWeight = FontWeight.Bold,
                            fontSize = 18.sp,
                            color = MaterialTheme.colors.primary
                        )
                    }
                }

                Spacer(modifier = Modifier.height(24.dp))

                // 按钮
                Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) {
                    TextButton(onClick = onDismiss) {
                        Text("取消", color = MaterialTheme.colors.onSurface.copy(alpha = 0.7f))
                    }
                    Spacer(modifier = Modifier.width(16.dp))
                    Button(
                        onClick = {
                            // 验证输入
                            val feeStandardValue = feeStandard.toDoubleOrNull()
                            val studentCountValue = studentCount.toIntOrNull()
                            val attendanceDaysValue = attendanceDays.toIntOrNull() ?: 22

                            if (className.isNotBlank() && feeStandardValue != null && studentCountValue != null) {
                                val record = FeeRecord(
                                    className = className,
                                    feeStandard = feeStandardValue,
                                    date = selectedDate,
                                    studentCount = studentCountValue,
                                    isFullAttendance = isFullAttendance,
                                    attendanceDays = attendanceDaysValue
                                )
                                onConfirm(record)
                            }
                        },
                        colors = ButtonDefaults.buttonColors(
                            backgroundColor = MaterialTheme.colors.primary,
                            contentColor = MaterialTheme.colors.onPrimary
                        )
                    ) {
                        Text("确认")
                    }
                }
            }
        }
    }
}

// 按班级分类显示费用记录
@Composable
fun ClassBasedFeeDisplay(feeRecordsByClass: Map<String, List<FeeRecord>>) {
    LazyColumn(
        modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 16.dp),
        verticalArrangement = Arrangement.spacedBy(16.dp)
    ) {
        if (feeRecordsByClass.isEmpty()) {
            item {
                Card(
                    modifier = Modifier.fillMaxWidth(),
                    elevation = 0.dp, // 禁用阴影
                    backgroundColor = MaterialTheme.colors.surface,
                    shape = RoundedCornerShape(8.dp)
                ) {
                    Box(
                        modifier = Modifier.fillMaxWidth().wrapContentHeight(),
                        contentAlignment = Alignment.Center,
                    ) {
                        Text(
                            modifier = Modifier.height(120.dp).wrapContentSize(Alignment.Center),
                            text = "暂无数据",
                            color = MaterialTheme.colors.onSurface.copy(alpha = 0.6f)
                        )
                    }
                }
            }
        } else {
            // 为每个班级创建一个卡片
            feeRecordsByClass.forEach { (className, records) ->
                item {
                    ClassFeeCard(className = className, feeRecords = records)
                }
            }
        }
    }
}

@Composable
fun ClassFeeCard(className: String, feeRecords: List<FeeRecord>) {
    val classTotal = remember(feeRecords) {
        feeRecords.sumOf { it.amount }
    }

    Card(
        modifier = Modifier.fillMaxWidth(),
        elevation = 4.dp,
        backgroundColor = MaterialTheme.colors.surface,
        shape = RoundedCornerShape(8.dp)
    ) {
        Column(modifier = Modifier.padding(16.dp)) {
            // 班级标题和总金额
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    className,
                    fontSize = 20.sp,
                    fontWeight = FontWeight.Bold,
                    color = MaterialTheme.colors.primary
                )
                Text(
                    "¥${(round(classTotal * 100) / 100).toString()}",
                    fontSize = 18.sp,
                    fontWeight = FontWeight.Bold,
                    color = MaterialTheme.colors.primary
                )
            }

            Spacer(modifier = Modifier.height(16.dp))

            // 表头
            Surface(
                color = MaterialTheme.colors.primary.copy(alpha = 0.1f),
                modifier = Modifier.fillMaxWidth(),
                shape = RoundedCornerShape(4.dp)
            ) {
                Row(modifier = Modifier.fillMaxWidth().padding(12.dp)) {
                    TableHeaderCell(text = "日期", modifier = Modifier.weight(1f))
                    TableHeaderCell(text = "收费标准", modifier = Modifier.weight(1f))
                    TableHeaderCell(text = "人数", modifier = Modifier.weight(0.7f))
                    TableHeaderCell(text = "满勤", modifier = Modifier.weight(0.7f))
                    TableHeaderCell(text = "上课天数", modifier = Modifier.weight(0.7f))
                    TableHeaderCell(text = "金额", modifier = Modifier.weight(1f))
                }
            }

            // 表格内容
            Column {
                feeRecords.forEach { record ->
                    Row(
                        modifier = Modifier.fillMaxWidth().padding(vertical = 8.dp),
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        // 显示年月而不是完整日期
                        TableCell(
                            text = "${record.date.year}年${record.date.monthNumber}月",
                            modifier = Modifier.weight(1f)
                        )
                        TableCell(text = "¥${record.feeStandard}", modifier = Modifier.weight(1f))
                        TableCell(text = "${record.studentCount}", modifier = Modifier.weight(0.7f))
                        TableCell(
                            text = if (record.isFullAttendance) "是" else "否",
                            modifier = Modifier.weight(0.7f)
                        )
                        TableCell(
                            text = "${record.attendanceDays}",
                            modifier = Modifier.weight(0.7f)
                        )
                        TableCell(
                            text = "¥${(round(record.amount * 100) / 100).toString()}",
                            modifier = Modifier.weight(1f),
                            color = MaterialTheme.colors.primary
                        )
                    }
                    Divider(color = MaterialTheme.colors.onSurface.copy(alpha = 0.1f))
                }
            }
        }
    }
}